<!--
 * @Author: wei_jt@ecidi.com
 * @Date: 2019-11-09 16:08:59
 * @LastEditors: chen_yt
 * @LastEditTime: 2022-04-11 09:30:53
 * @Description: 功能权限列表页
 -->
<template>
  <div style="height: 100%" class="app-auth">
    <fks-query-page
      ref="table"
      v-loading="loading"
      :data="list"
      height="100%"
      :current-page.sync="currentPage"
      :page-sizes="[20, 50, 100]"
      :page-size.sync="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      :table-name="LANG[tableName] || tableName"
      @query="getButtons"
      @selection-change="handleSelect"
      @sort-change="sortHandler"
    >
      <template slot="singleSearch">
        <div class="single-searchBox">
          <fks-button v-permission="['fun:import']" @click="importData">
            <i class="fks-icon-import" />
            <span>{{ LANG.IMPORT }}</span>
          </fks-button>
          <fks-button v-permission="['fun:export']" @click="exportData">
            <i class="fks-icon-export" />
            <span>{{ LANG.EXPORT }}</span>
          </fks-button>
          <fks-button
            v-permission="['fun:add']"
            type="primary"
            icon="fks-icon-plus"
            @click="addRootNode"
          >
            {{ LANG.ADD }}
          </fks-button>
        </div>
      </template>
      <template>
        <fks-table-column type="selection" width="55" />
        <fks-table-column
          type="index"
          label="#"
          align="center"
          min-width="50px"
        />
        <fks-table-column
          prop="name"
          :label="LANG.NAME"
          sortable="custom"
          header-align="center"
          align="left"
        />
        <fks-table-column
          prop="code"
          :label="LANG.CODE"
          header-align="center"
          align="left"
        />
        <fks-table-column
          prop="url"
          :label="LANG.INTERFACE"
          header-align="center"
          align="left"
        />
        <fks-table-column
          prop="isAuth"
          :label="LANG.IS_AUTH"
          align="center"
          sortable="custom"
        >
          <template slot-scope="scope">
            {{ scope.row.isAuth ? LANG.AUTHORIZED : LANG.UNAUTHORIZED }}
          </template>
        </fks-table-column>
        <fks-table-column
          prop="isGeneral"
          :render-header="roleSelect"
          header-row-class-name="selectRole"
          align="center"
          header-align="center"
          min-width="80"
        >
          <div slot-scope="scope">
            <span v-if="scope.row.isGeneral">
              {{ LANG.COMMON }}
            </span>
            <span v-if="!scope.row.isGeneral">
              {{ LANG.PRIVATE }}
            </span>
          </div>
        </fks-table-column>
        <fks-table-column :label="LANG.OPERATION" width="100" align="left">
          <template slot-scope="scope">
            <fks-button
              v-permission="['fun:edit']"
              :disabled="!canEditCommonMenu(scope.row)"
              type="text"
              @click="edit(scope.row)"
            >
              {{ LANG.EDIT }}
            </fks-button>
            <fks-button
              v-permission="['fun:delete']"
              :disabled="!canEditCommonMenu(scope.row)"
              danger-text
              @click.native="handleDelete(scope.row.id)"
            >
              {{ LANG.DELETE }}
            </fks-button>
          </template>
        </fks-table-column>
      </template>
    </fks-query-page>
    <import-buttons :import-visible.sync="importVisible" :menu-id="menuId" />
    <fun-detail :data="node" :visible.sync="visible" :menu-id="menuId" />
  </div>
</template>
<script>
import * as Auth from './api'
import FunDetail from './FunDetail'
import ImportButtons from './ImportButtons'
import { exportFile } from '@/utils/file'
import { AUTH_PORTAL } from '@/store/Getter/getterTypes.js'
export default {
  name: 'MenuManagement',
  components: {
    FunDetail,
    ImportButtons
  },
  props: {
    menuId: {
      default: ''
    },
    tableName: {}
  },
  data() {
    return {
      keywords: '',
      node: {},
      visible: false,
      list: [],
      pageSize: 20,
      currentPage: 1,
      total: 0,
      sort: '',
      columnName: '',
      loading: false,
      importVisible: false,
      checkedList: [],
      currentType: 0,
      isGeneral: ''
    }
  },
  computed: {
    multiPortal() {
      return this.$store.getters.multiPortal
    },
    currentEditPotal() {
      return this.$store.getters[AUTH_PORTAL]
    },
    menuIndex() {
      return { menuId: this.menuId, portalId: this.currentEditPotal.portalId }
    },
    funcType() {
      let data = [
        { name: this.LANG.ALL, isGeneral: '' },
        { name: this.LANG.COMMON, isGeneral: true },
        { name: this.LANG.PRIVATE, isGeneral: false }
      ]
      return data
    }
  },
  watch: {
    menuIndex() {
      this.getButtons()
    },
    currentType: {
      handler: function (val) {
        this.clearSort()
        this.isGeneral = this.funcType[val].isGeneral
        this.getButtons()
      }
    }
  },
  mounted() {
    this.currentType = 0
    this.getButtons()
  },
  beforeDestroy() {},
  methods: {
    /**
     * @description: 切换角色是否通用后清空排序条件
     */
    clearSort() {
      this.$refs['table'].clearSort()
      this.sort = ''
      this.columnName = ''
    },
    roleSelect(h, { column, $index }) {
      // 给表格添加包裹的div
      return h('div', {}, [
        // 添加el-select 标签
        h(
          'fks-select',
          {
            on: {
              input: (value) => {
                this.currentType = value
              }
            },
            props: {
              value: this.currentType, // 给el-select 设置值（也是相当于v-model）
              size: 'small',
              class: 'selectRole',
              style: {
                height: '25px',
                width: '110px',
                paddingLeft: '0px',
                paddingRight: '0px'
              }
            }
          },
          [
            //给当前 el-select 设置 el-option
            this.funcType.map((item, index) => {
              return h('fks-option', {
                props: {
                  value: index,
                  label: item.name
                }
              })
            })
          ]
        )
      ])
    },
    canEditCommonMenu(content) {
      if (!this.multiPortal) {
        return true
      }
      if (this.currentEditPotal.portalId && content.isGeneral) {
        return false
      }
      return true
    },
    sortHandler(data) {
      let params = {}
      if (!data.order) {
        this.sort = ''
        this.columnName = ''
      } else {
        this.sort = data.order == 'ascending' ? 'asc' : 'desc'
        this.columnName = data.prop == 'name' ? 'name' : 'is_auth '
      }
      params = {
        menuId: this.menuId,
        pageNo: this.currentPage,
        pageSize: this.pageSize,
        sort: this.sort,
        columnName: this.columnName
      }
      this.getButtonsList(params)
    },
    getButtons() {
      if (!this.menuId) {
        return false
      }
      let params = {
        menuId: this.menuId,
        pageNo: this.currentPage,
        pageSize: this.pageSize,
        sort: this.sort,
        columnName: this.columnName
      }
      this.getButtonsList(params)
    },
    getButtonsList(params) {
      let param = {
        ...params,
        ...this.currentEditPotal,
        isGeneral: this.isGeneral
      }
      Auth.getButtonPage(param)
        .then((res) => {
          if (res.status) {
            this.list = res.data.list
            this.total = res.data.total
          } else {
            this.list = []
          }
          this.loading = false
        })
        .catch((error) => {
          this.loading = false
          this.list = []
          this.total = 0
        })
    },
    edit(data) {
      this.node = data
      this.node.operate_type = 'edit'
      this.visible = true
    },
    /**
     * @description: 删除菜单
     * @param {id}
     * @return:
     */
    handleDelete(id) {
      this.$confirm(this.LANG.CONFIRM_TIPS, this.LANG.TIPS, {
        type: 'warning',
        confirmButtonText: this.LANG.DELETE,
        cancelButtonText: this.LANG.CANCEL,
        confirmButtonClass: 'fks-button--danger',
        deleteMode: true
      })
        .then(() => {
          Auth.deleteButton(id)
            .then((res) => {
              if (res.status) {
                this.$message({
                  type: 'success',
                  message: this.LANG.DELETE_SUCCESS
                })
                this.getButtons()
              }
            })
            .catch(() => {})
        })
        .catch(() => {})
    },
    /**
     * @description: 新增根菜单节点-打开弹窗
     * @param {}
     * @return:
     */
    handleSelect(val) {
      this.checkedList = []
      this.checkedList = val
    },
    importData() {
      this.importVisible = true
    },
    exportData() {
      if (!this.checkedList || !this.checkedList.length) {
        return this.$message.warning(this.LANG.EXPORT_REQUIRED)
      }
      Auth.exportButton(this.checkedList)
        .then((res) => {
          if (res.status) {
            this.$message.success(this.LANG.EXPORT_SUCCESS)
            exportFile(res)
            this.$refs.table.$children[0].clearSelection()
            this.checkedList = []
          }
        })
        .catch(() => {
          this.checkedList = []
          this.$refs.table.$children[0].clearSelection()
        })
    },
    addRootNode() {
      this.node = { operate_type: 'add' }
      this.visible = true
    },
    /**
     * @description: 选中菜单树节点
     * @param {data}
     * @return:
     */
    setCurrentNode(data) {
      this.$nextTick(() => {
        if (!data && this.authorities.length > 0) {
          this.$refs.routeTree &&
            this.$refs.routeTree.setCurrentKey(this.authorities[0].id)
          this.node = this.authorities[0]
        } else {
          this.node = data
          setTimeout(() => {
            this.$refs.authTree && this.$refs.authTree.setCurrentKey(data.id)
          }, 500)
        }
      })
    },
    /**
     * @description: 筛选菜单
     * @param {type}
     * @return:
     */
    filter(data, cell, callback) {
      const ky = this.keywords.toLowerCase()
      const list = []
      for (const item of data) {
        if (item.children) {
          const arr = Object.assign({}, item)
          arr.children = []
          const next = cell + 1
          this.filter(item.children, next, (val) => {
            if (!this.map[val.id]) {
              arr.children.push(val)
              this.map[val.id] = true
            }
            if (cell == 1 && !this.map[arr.id]) {
              list.push(arr)
              this.map[arr.id] = true
            }
            if (cell != 1) {
              callback(arr)
            }
          })
          if (
            (item.name.toLowerCase().includes(ky) ||
              (item.routerPath &&
                item.routerPath.toLowerCase().includes(ky))) &&
            !this.map[arr.id]
          ) {
            if (cell == 1) {
              list.push(arr)
            } else {
              callback(arr)
            }
          }
        } else {
          if (
            item.name.toLowerCase().includes(ky) ||
            (item.routerPath && item.routerPath.toLowerCase().includes(ky))
          ) {
            if (cell == 1) {
              list.push(item)
            } else {
              callback(item)
            }
          }
        }
      }
      return list
    },
    search() {
      this.currentPage = 1
      this.fetchData()
    },
    /**
     * @description: 展开/收起表格
     * @param {type}
     * @return:
     */
    expand() {
      // let expandRows = this.$refs.table.store.expandRowKeys
      // expandRows.forEach(row => {
      //   this.$refs.table.toggleRowExpansion(row,false)
      // })
    }
  }
}
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
::v-deep .fks-table th > .cell .fks-input--small .fks-input__inner {
  border: none;
  text-align: center;
  background-color: transparent;
}

::v-deep .fks-select .fks-input .fks-select__caret {
  margin-top: -0.5px;
}

::v-deep .fks-table .fks-input--suffix .fks-input__inner {
  padding-left: 30px !important;
}
</style>